<template>
    <!-- 搜索框 -->
    <view class="navbar">
        <view class="statusBar" :style="{height:getStatusBarHeight()+'px'}"></view>
        <view class="titleBar" :style="{height:getTitleBarHeight()+'px',marginLeft:getLeftIconLeft()+'px'}" >
            <uni-search-bar 
                @confirm="onSearch" 
                @input="onInput" 
                :radius="30" 
                placeholder="请输入搜索内容"
                cancelButton="none"
                bgColor="#F8F8F8"
                :showAction="false"
                class="search-box"
            ></uni-search-bar>
        </view>
    </view>
    
    <!-- 填充区域->为了让固定的搜索框不遮盖内容 -->
    <view class="fill" :style="{height: getNavBarHeight() +'px'}"/>
    
    <!-- 最近搜索区域 - 搜索时隐藏 -->
    <view class="recent-search" v-if="!isSearching && searchHistory.length > 0">
        <view class="search-header">
            <text class="title">最近搜索</text>
            <uni-icons type="trash" size="25" @click="showClearConfirm" />
        </view>
        <view class="search-tags">
            <view class="tag" v-for="(item, index) in searchHistory.slice(0, 20)" :key="index" @click="handleHistorySearch(item)">
                <text class="tag-text">{{ item }}</text>
            </view>
        </view>
    </view>
    
    <!-- 搜索结果区域 - 搜索时显示 -->
    <view class="result" v-else>
        <!-- 联系人 -->
        <view class="section" v-if="searchResults.contacts.length > 0">
            <view class="section-header">
                <text class="section-title">联系人</text>
                <text class="more" @click="toggleShowAll('contacts')">更多 > </text>
            </view>
            <view class="list">
                <view 
                    class="item" 
                    v-for="(item, index) in showContacts" 
                    :key="index"
                    @click="handleItemClick('contacts', item)"
                    :class="{ 'active': activeItem === index && activeType === 'contacts' }"
                    @touchstart="handleTouchStart('contacts', index)"
                    @touchend="handleTouchEnd"
                    @touchmove="handleTouchMove"
                >
                    <image :src="'/static/logo.png'" class="avatar" />
                    <view class="info">
                        <text class="nickname">{{ item.nickname }} ({{ item.qq }})</text>
                        <text class="desc">来自分组:{{ item.group }}</text>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 群聊 -->
        <view class="section" v-if="searchResults.groups.length > 0">
            <view class="section-header">
                <text class="section-title">群聊</text>
                <text class="more" @click="toggleShowAll('groups')">更多 > </text>
            </view>
            <view class="list">
                <view 
                    class="item" 
                    v-for="(item, index) in showGroups" 
                    :key="index"
                    @click="handleItemClick('groups', item)"
                    :class="{ 'active': activeItem === index && activeType === 'groups' }"
                    @touchstart="handleTouchStart('groups', index)"
                    @touchend="handleTouchEnd"
                    @touchmove="handleTouchMove"
                >
                    <image :src="'/static/logo.png'" class="avatar" />
                    <view class="info">
                        <text class="nickname">{{ item.name }} ({{ item.qq }})</text>
                        <text class="desc">包含:{{ item.members.join('、') }}</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIconLeft } from "@/utils/system.js"

// 搜索历史数据
const searchHistory = ref([])
// 是否处于搜索状态
const isSearching = ref(false)
// 搜索结果数据
const searchResults = ref({
    contacts: [
        { nickname: '清风', qq: '3860836863', group: '我的好友' },
        { nickname: '清风明月', qq: '862677108', group: '我的好友' },
        { nickname: '明月清风', qq: '362856178', group: '我的好友' },
        { nickname: '测试联系人', qq: '123456789', group: '我的好友' },
    ],
    groups: [
        { name: '清风学习交流群', qq: '1002834200', members: ['清风'] },
        { name: '山羊の前端小窝', qq: '673582949', members: ['明月清风','清风与酒','清风明月'] },
        { name: '程序员派单3群', qq: '1025436201', members: ['明月清风'] },
        { name: '测试群聊', qq: '987654321', members: ['测试成员'] },
    ]
})
// 控制“更多”后是否展示全部
const showAllStatus = ref({
    contacts: false,
    groups: false
})
// 当前激活的项索引和类型
const activeItem = ref(-1)
const activeType = ref('')
// 触摸状态
const isTouching = ref(false)

// 从本地存储加载搜索历史
const loadSearchHistory = () => {
    try {
        const history = uni.getStorageSync('searchHistory')
        if (history) {
            searchHistory.value = JSON.parse(history)
        }
    } catch (e) {
        console.error('加载搜索历史失败', e)
    }
}

// 保存搜索历史到本地存储
const saveSearchHistory = () => {
    try {
        const limitedHistory = searchHistory.value.slice(0, 20)
        uni.setStorageSync('searchHistory', JSON.stringify(limitedHistory))
    } catch (e) {
        console.error('保存搜索历史失败', e)
    }
}

// 添加搜索记录
const addSearchHistory = (keyword) => {
    if (!keyword) return
    
    const index = searchHistory.value.findIndex(item => item === keyword)
    if (index !== -1) {
        searchHistory.value.splice(index, 1)
    }
    
    searchHistory.value.unshift(keyword)
}

// 搜索事件处理
const onSearch = (e) => {
    const keyword = (e?.detail?.value || e?.value || '').trim()
    
    if (keyword) {
        isSearching.value = true
        addSearchHistory(keyword)
        saveSearchHistory()
        performSearch(keyword)
    }
}

// 执行实际搜索逻辑
const performSearch = (keyword) => {
    console.log('执行搜索:', keyword)
    // 实际项目中替换为API调用
}

// 输入事件处理
const onInput = (e) => {
    const inputValue = e?.detail?.value || e?.value || ''
    
    if (inputValue.trim() === '') {
        isSearching.value = false
    }
}

// 处理历史记录搜索
const handleHistorySearch = (keyword) => {
    isSearching.value = true
    addSearchHistory(keyword)
    saveSearchHistory()
    performSearch(keyword)
}

// 显示确认对话框
const showClearConfirm = () => {
    uni.showModal({
        title: '确认清除',
        content: '确定要清除所有搜索历史吗？',
        confirmText: '确认',
        cancelText: '取消',
        success: (res) => {
            if (res.confirm) {
                clearAllHistory()
            }
        }
    })
}

// 清空所有历史记录
const clearAllHistory = () => {
    searchHistory.value = []
    saveSearchHistory()
}

// 切换“更多”显示全部/收起
const toggleShowAll = (type) => {
    showAllStatus.value[type] = !showAllStatus.value[type]
}

// 计算要显示的联系人
const showContacts = computed(() => {
    return showAllStatus.value.contacts 
        ? searchResults.value.contacts 
        : searchResults.value.contacts.slice(0, 3)
})

// 计算要显示的群聊
const showGroups = computed(() => {
    return showAllStatus.value.groups 
        ? searchResults.value.groups 
        : searchResults.value.groups.slice(0, 3)
})

// 处理项目点击
const handleItemClick = (type, item) => {
    console.log(`点击${type === 'contacts' ? '联系人' : '群聊'}:`, item)
    
    // 模拟导航到详情页
    setTimeout(() => {
        uni.showToast({
            title: `进入${type === 'contacts' ? '联系人' : '群聊'}: ${type === 'contacts' ? item.nickname : item.name}`,
            icon: 'none'
        })
    }, 200)
}

// 触摸开始
const handleTouchStart = (type, index) => {
    isTouching.value = true
    activeItem.value = index
    activeType.value = type
}

// 触摸结束
const handleTouchEnd = () => {
    setTimeout(() => {
        if (isTouching.value) {
            activeItem.value = -1
            activeType.value = ''
            isTouching.value = false
        }
    }, 200)
}

// 触摸移动（防止滚动时触发点击效果）
const handleTouchMove = () => {
    isTouching.value = false
    activeItem.value = -1
    activeType.value = ''
}

// 组件挂载时加载历史记录
onMounted(() => {
    loadSearchHistory()
})

// 组件卸载时保存历史记录
onUnmounted(() => {
    saveSearchHistory()
})
</script>

<style lang="scss" scoped>
.navbar{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 10;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    .titleBar{
        display: flex;
        align-items: center;
        padding: 0 30rpx;
    }
    .search-box {
        width: 100%;
    }
}

.fill {
    width: 100%;
}

.recent-search {
    width: 100%;
    padding: 20rpx 30rpx;
    background-color: #fff;
    z-index: 5;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    
    .search-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 60rpx;
        margin-bottom: 15rpx;
        margin-top: 15rpx;
        margin-right: 25px;
        
        .title {
            font-size: 28rpx;
            color: #333;
        }
    }
    
    .search-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 15rpx;
        
        .tag {
            display: flex;
            align-items: center;
            padding: 10rpx 20rpx;
            background-color: #f5f5f5;
            border-radius: 30rpx;
            font-size: 26rpx;
            color: #666;
            cursor: pointer;
        }
    }
}

.result {
    padding: 20rpx 30rpx;
    background-color: #fff;
}

.section {
    margin-bottom: 30rpx;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 15rpx;
}

.more {
    font-size: 24rpx;
    color: #999;
    cursor: pointer;
}

.list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.item {
    display: flex;
    align-items: center;
    gap: 15rpx;
    padding: 20rpx;
    border-radius: 12rpx;
    background-color: #fff;
    transition: all 0.2s;
    
    // 点击效果
    &.active {
        background-color: #f0f0f0;
        transform: scale(0.98);
    }
    
    // 触摸反馈
    &:active {
        background-color: #f5f5f5;
    }
}

.avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 8rpx;
}

.info {
    display: flex;
    flex-direction: column;
    gap: 5rpx;
}

.nickname {
    font-size: 28rpx;
    color: #333;
}

.desc {
    font-size: 24rpx;
    color: #999;
}
</style>